package com.mofang.model;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mofang.dao.remote.RemoteRecommendationDao;
import com.pactera.framework.exception.NetworkException;
import com.pactera.framework.exception.TimeoutException;
import com.pactera.framework.http.HttpResult;
import com.pactera.framework.model.MapEntity;
import com.pactera.framework.util.Loger;

/**
 * @author Gong 推荐买房
 */
public class RecommendationModel extends MoFangBaseModel {

	public static final int Id = 1;
	public static final int Recommend_person_id = 2;
	public static final int Recommend_person_name = 3;
	public static final int Be_recommend_person_id = 4;
	public static final int Be_recommend_person_name = 5;
	public static final int Be_recommend_person_phone = 6;
	public static final int Intention_city = 7;
	public static final int Intention_district = 8;
	public static final int Intention_building = 9;
	public static final int Intention_area = 10;
	public static final int Intention_total_price = 11;
	public static final int Special_Requirement = 12;

	/**
	 * 获得全部推荐信息
	 * @param userId
	 * @return
	 * @throws TimeoutException
	 * @throws NetworkException
	 */
	public ArrayList<MapEntity> getRecommendationList(String userId)
			throws TimeoutException, NetworkException {
		// TODO Auto-generated method stub
		HttpResult httpResult = new RemoteRecommendationDao()
				.getRecommendationList(userId);
		String response = preParseHttpResult(httpResult);
		Loger.d(response);
		ArrayList<MapEntity> mapList = new ArrayList<MapEntity>();
		try {
			JSONObject data = preParseResponse(response);
			if (data != null) {

				JSONArray dataJsonArray = data.getJSONArray("data");
				int dataLength = dataJsonArray.length();
				if (dataLength <= 0) {
					return null;
				}
				for (int i = 0; i < dataLength; i++) {
					JSONObject dataJsonObj = dataJsonArray.getJSONObject(i);
					MapEntity mapEntity = new MapEntity();
					if (dataJsonObj.has("be_recommend_person_name")) {
						mapEntity.setValue(Be_recommend_person_name,
								dataJsonObj.getString("rep_id"));
					}
					mapList.add(mapEntity);
				}

			}
			// jsonObject.getJSONArray(name);
			// XXX
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
		return mapList;
	}

	/**
	 * 上传推荐信息
	 * @param entity
	 * @return
	 * @throws NetworkException
	 */
	public String addRecommend(MapEntity entity) throws NetworkException {
		HttpResult httpResult = new RemoteRecommendationDao()
				.addRecommendation(entity.getString(Be_recommend_person_name));
		String response = preParseHttpResult(httpResult);
		Loger.d(response);
		try {
			preParseResponse(response);
		} catch (JSONException e) {
			e.printStackTrace();
			return "false";
		}
		return "true";
	}

}
